/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.pajmas.daydream.building;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import org.apache.commons.collections4.IteratorUtils;
import org.pajamas.protocol.Builder;

import java.util.Iterator;
import java.util.Set;

/**
 * @author william
 * @since 2024/2/29
 */
public abstract class AbstractEzBuilder<T> implements Builder<T> {
    Set<Customizer<T, AbstractEzBuilder<T>>> customizers;

    protected AbstractEzBuilder() {
        this.customizers = Sets.newHashSet();
    }

    @SuppressWarnings("unchecked")
    public AbstractEzBuilder<T> customizers(Iterator<? extends Customizer<T, ? extends AbstractEzBuilder<T>>> customizers) {
        this.customizers.clear();
        if (!IteratorUtils.isEmpty(customizers)) {
            Lists
                    .newArrayList(customizers)
                    .stream()
                    .map(customizer -> (Customizer<T, AbstractEzBuilder<T>>) customizer)
                    .forEach(this.customizers::add);
        }
        return this;
    }

    @Override
    public T build() {
        this.customizers.forEach(customizer -> customizer.customize(this));
        return this.internalBuild();
    }

    protected abstract T internalBuild();

    public interface Customizer<T, B extends AbstractEzBuilder<T>> extends org.pajamas.protocol.Customizer<B> {
        @Override
        void customize(B builder);
    }
}
